package com.example.myjavafx.controller;

import com.example.myjavafx.model.User;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.FileChooser;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

public class PersonnelSearchController {
    @FXML private ComboBox<String> searchTypeComboBox;
    @FXML private TextField searchTextField;
    @FXML private TableView<User> personnelTableView;
    @FXML private TableColumn<User, String> nameColumn;
    @FXML private TableColumn<User, String> departmentColumn;
    @FXML private TableColumn<User, String> positionColumn;
    @FXML private TableColumn<User, String> contactColumn;
    @FXML private Label resultCountLabel;
    @FXML private TextArea responseTextArea;

    private HttpClient httpClient;
    private Gson gson;
    private ObservableList<User> personnelList;

    public void initialize() {
        httpClient = HttpClient.newHttpClient();
        gson = new Gson();
        personnelList = FXCollections.observableArrayList();

        // 配置表格列
        nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        departmentColumn.setCellValueFactory(cellData -> cellData.getValue().departmentProperty());
        positionColumn.setCellValueFactory(cellData -> cellData.getValue().positionProperty());
        contactColumn.setCellValueFactory(cellData -> cellData.getValue().contactProperty());

        personnelTableView.setItems(personnelList);
    }

    @FXML
    private void searchPersonnel() {
        String searchType = searchTypeComboBox.getValue();
        String searchKeyword = searchTextField.getText().trim();

        if (searchType == null || searchKeyword.isEmpty()) {
            showAlert("搜索错误", "请选择搜索类型并输入关键词");
            return;
        }

        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("searchType", searchType);
        requestBody.addProperty("keyword", searchKeyword);

        sendSearchRequest(requestBody);
    }

    private void sendSearchRequest(JsonObject requestBody) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("http://your-backend-url/personnel/search"))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
                    .build();

            httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                    .thenAccept(response -> Platform.runLater(() -> {
                        int statusCode = response.statusCode();
                        String responseBody = response.body();
                        processSearchResponse(statusCode, responseBody);
                    }));
        } catch (Exception e) {
            showAlert("错误", "请求发送失败: " + e.getMessage());
        }
    }

    private void processSearchResponse(int statusCode, String responseBody) {
        responseTextArea.setText("状态码: " + statusCode + "\n响应内容: " + responseBody);

        try {
            JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);

            if (jsonResponse.has("personnel")) {
                JsonArray personnelArray = jsonResponse.getAsJsonArray("personnel");
                List<User> searchResults = gson.fromJson(personnelArray, new TypeToken<List<User>>(){}.getType());

                personnelList.clear();
                personnelList.addAll(searchResults);

                resultCountLabel.setText("共 " + searchResults.size() + " 条结果");
            } else {
                showAlert("搜索结果", "未找到匹配的人员");
            }
        } catch (Exception e) {
            showAlert("解析错误", "无法解析服务器响应: " + e.getMessage());
        }
    }

    @FXML
    private void exportResults() {
        if (personnelList.isEmpty()) {
            showAlert("导出错误", "没有可导出的数据");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出人员搜索结果");
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("CSV Files", "*.csv")
        );
        File selectedFile = fileChooser.showSaveDialog(null);

        if (selectedFile != null) {
            try (FileWriter writer = new FileWriter(selectedFile)) {
                // 写入CSV标题行
                writer.write("姓名,部门,职位,联系方式\n");

                // 写入数据行
                for (User user : personnelList) {
                    writer.write(String.format("%s,%s,%s,%s\n",
                        user.getName(),
                        user.getDepartment(),
                        user.getPosition(),
                        user.getContact()));
                }

                showAlert("导出成功", "人员搜索结果已导出到 " + selectedFile.getAbsolutePath());
            } catch (IOException e) {
                showAlert("导出错误", "导出文件时发生错误: " + e.getMessage());
            }
        }
    }

    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}